import { Effect } from 'umi';
import { message } from 'antd';
import { fetchAllTask, fetchTaskDetail} from '@/services/task';
import { fetchUsersByRole } from '@/services/user';
import { querySysDict } from '@/services/system';
import { TaskItem } from '@/types/task';
import { TradeResult } from '@/types/global';
import { BaseModelType } from './common';

export interface TaskModelState {
  rows?: TaskItem[];
  total?: number;
  pageSize?: number;
}

export interface TaskModelType extends BaseModelType {
  namespace: 'tasks';
  state: TaskModelState;
  effects: {
    fetchTaskInitParams: Effect;
    fetchAllTask: Effect;
    fetchTaskDetail: Effect;
    unMount: Effect;
  };
  // reducers: {
  //   updateState: Reducer<ParamModelState>;
  // };
}

const TaskModel: TaskModelType = {
  namespace: 'tasks',

  state: {
    rows: [],
    total: 0,
    pageSize: 10,
  },

  effects: {
    *fetchTaskInitParams({ payload }, sagaEffects) {
      const { all, call, put } = sagaEffects;
      try {
        const [ devUserListResponse, testUserListResponse, systemListResponse, tradeTaskStateResponse, taskNameResponse ] = yield all([
          call(fetchUsersByRole, {
            roleCode: 'developer'
          }),
          call(fetchUsersByRole, {
            roleCode: 'tester'
          }),
          call(querySysDict, {
            dictName: 'system'
          }),
          call(querySysDict, {
            dictName: 'tradeTaskStatus'
          }),
          call(querySysDict, {
            dictName: 'tradeTaskName'
          }),
        ]);
        const devSuccess =  devUserListResponse.success;
        const testSuccess =  testUserListResponse.success;
        const sysSuccess =  systemListResponse.success;
        const statusSuccess =  tradeTaskStateResponse.success;
        const taskSuccess =  taskNameResponse.success;
        if (devSuccess && testSuccess && sysSuccess && statusSuccess && taskSuccess) {
          const developerData = devUserListResponse.result.userList;
          const testerData = testUserListResponse.result.userList;
          const userResult  = {
            developerData,
            testerData
          };
          console.info(userResult);
          const result = {
            systemData: [...systemListResponse.result],
            taskTypeData: [...taskNameResponse.result],
            taskStatusData: [...tradeTaskStateResponse.result],
          };
          yield put({ type: 'users/updateState', payload: userResult });
          yield put({ type: 'systems/updateState', payload: result });
        }
      } catch(e) {
        console.error(e);
        message.error('数据获取失败');
      }
    },
    *fetchAllTask({ payload }, sagaEffects) {
      const { call, put } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(fetchAllTask, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          // 通讯成功取出数据
          const { result } = response;
          // 更新表格数据
          yield put({ type: 'updateState', payload: result });
        } else {
          // message.error(`${response.errorCode}:${response.errorMsg}`); // 打印错误信息
        }
      } catch(e) {
        console.info(e);
        message.error('数据获取失败'); // 打印错误信息
      }
    },
    *fetchTaskDetail({ payload }, sagaEffects) {
      const { call } = sagaEffects;
      try {
        // 获取服务端数据
        // call 第一个参数为一个函数，后面的参数为函数调用时的入参
        console.log(JSON.stringify(payload));
        const response: TradeResult = yield call(fetchTaskDetail, payload);
        // console.log(JSON.stringify(response));
        const { success } = response;
        if (success) {
          return response;
        }
        return false;
      } catch(e) {
        console.info(e);
        message.error('数据获取失败'); // 打印错误信息
        return false;
      }
    },
    *unMount({ payload }, sagaEffects) {
      const { put } = sagaEffects;
      const result = {
        rows: [],
        total: 0,
        pageSize: 10,
      }
      yield put({ type: 'updateState', payload: result });
    }
  },

  reducers: {
    updateState(state, { payload }) {
      console.info(payload);
      return {
        ...state,
        ...payload
      }
    },
  },
}

export default TaskModel;